package com.aust.dynamicProxy.test4;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Arrays;

public class CalculatorHandler implements InvocationHandler {
    private Object object;
    private String userName;

    public CalculatorHandler(Object object, String userName) {
        this.object = object;
        this.userName = userName;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        if (method.getName().equals("add") || method.getName().equals("mul")) {
            System.out.println("此方法是加法或者乘法");
            return getObject(method, args);
        } else if (userName.equals("admin") && method.getName().equals("sub")) {
            System.out.println("当前只有管理员可以执行减法操作");
            return getObject(method, args);
        } else if (method.getName().equals("div")) {
            return getObject(method, args);
        } else {
            System.out.println("当前用户没有权限执行减法运算，默认输出-999999999");
            return -999999999;
        }
    }

    private Object getObject(Method method, Object[] args) throws Exception {
        System.out.println("方法名：" + method.getName());
        System.out.println("参数：" + Arrays.toString(args));
        long start = System.currentTimeMillis();
        Object result = method.invoke(object, args);
        long end = System.currentTimeMillis();
        System.out.println("执行时长为：" + (end - start) + "ms");
        return result;
    }
}